package com.qiyuesuo.service.impl;

import com.qiyuesuo.entity.MyFile;
import com.qiyuesuo.exception.BusinessException;
import com.qiyuesuo.exception.code.BaseResponseCode;
import com.qiyuesuo.mapper.MyFileMapper;
import com.qiyuesuo.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.io.File;

@Service
@Slf4j
public class FileServiceImpl implements FileService {
    //注入保存路径
    @Value("${file.path}")
    private String FILE_PATH;
    //注入文件地址
    @Value("${file.base-url}")
    private String BASE_URL;
    //拿到文件DAO层实例
    @Autowired
    private MyFileMapper myFileMapper;
    @Override
    public String upload(MultipartFile file) {
         //设置主键ID
        String uuid= UUID.randomUUID().toString();
        //拿到原始名称
        String originalFilename = file.getOriginalFilename();
        //拿到扩展名称
        String extensionName=originalFilename.substring(originalFilename.lastIndexOf(".")+1).toLowerCase();
        //重命名文件
        String fileId= UUID.randomUUID().toString();
        //创建新文件名
        String fileName=fileId+"."+extensionName;
        //创建以日期为格式的文件目录
        SimpleDateFormat formatter= new SimpleDateFormat("yyyyMMdd");
        Date date = new Date(System.currentTimeMillis());
        String directoryName = formatter.format(date);
        File destFile=new File(FILE_PATH+directoryName+'/'+fileName);
        //在创建文件的时候，避免其文件所在的 文件夹不存在，然后抛出异常
        if(!destFile.getParentFile().exists()){
            destFile.getParentFile().mkdirs();
        }
        //设定文件保存路径
        String fileUrl=BASE_URL+directoryName+'/'+fileName;
        try {
            //复制文件到指定目录
            file.transferTo(destFile);
            //保存当前文件的相关信息到DB
            MyFile myFile=new MyFile();
            myFile.setId(uuid);
            myFile.setFileName(fileName);
            myFile.setOriginalName(originalFilename);
            myFile.setExtensionName(extensionName);
            myFile.setFileUrl(fileUrl);
            myFile.setCreateTime(new Date());
            //计算文件大小
            myFile.setSize(FileUtils.byteCountToDisplaySize(file.getSize()));
            int i = myFileMapper.insertSelective(myFile);
            //插入失败处理
            if(i!=1){
                throw new BusinessException(BaseResponseCode.UPLOAD_FILE_ERROR);
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("e:{}",e);
            throw new BusinessException(BaseResponseCode.UPLOAD_FILE_ERROR);
        }
        return uuid;
    }

    @Override
    public void download(String fileId, HttpServletResponse response) {
        //根据文件ID查询数据库
        MyFile file = myFileMapper.selectByPrimaryKey(fileId);
        //判断文件是否存在
        if(file==null){
            System.out.println("文件不存在！");
            //设置异常响应状态码
            response.setStatus(410);
            throw new BusinessException(BaseResponseCode.DOWNLOAD_FILE_ERROR);
        }
        try {
            //设置文件类型，以流的形式进行写入
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            //获取原始文件名称
            String fileName=new String(file.getOriginalName().getBytes("UTF-8"),"ISO-8859-1");
            //配置响应头部，以附件形式下载
            response.setHeader("content-disposition",String.format("filename=%s",fileName));
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException(BaseResponseCode.DOWNLOAD_FILE_ERROR);
        }
        //写入操作
        ServletOutputStream outputStream=null;
        try {
            //获取文件
            //获取文件路径
            String fileUrl = file.getFileUrl();
            fileUrl = fileUrl.trim();
            fileUrl = fileUrl.substring(fileUrl.indexOf("qiyuesuo")+1);
            String fileName = fileUrl.substring(fileUrl.indexOf('/')+1);
            File myFile = new File(FILE_PATH + fileName);
            //获取输出流
            outputStream = response.getOutputStream();
            //写入
            IOUtils.write(FileUtils.readFileToByteArray(myFile),outputStream);
        } catch (IOException e) {
            //设置异常响应状态码
            response.setStatus(410);
            throw new BusinessException(BaseResponseCode.DOWNLOAD_FILE_ERROR);
        }finally {
            //判断并关闭写入流
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    //设置异常响应状态码
                    response.setStatus(410);
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public MyFile getFileInfo(String fileId) {
        MyFile myFile  = myFileMapper.selectByPrimaryKey(fileId);
        return myFile;
    }


}
